package com.ericcson.innerportalapp;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;

import com.ericcson.innerportalapp.ToDoListArrayAdapter.OnEditItemSelectListener;

import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.util.JsonReader;
import android.util.JsonWriter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class ToDoListActivity extends Activity implements OnEditItemSelectListener {

	private ArrayList<ToDoItem> toDoItems = new ArrayList<ToDoItem>();
	private ToDoListFragment toDoListFragment;
	private ToDoListArrayAdapter toDoListArrayAdapter;
	private Menu menu;

	public ArrayList<ToDoItem> getToDoItems() {
		return toDoItems;
	}

	public void setToDoItems(ArrayList<ToDoItem> toDoItems) {
		this.toDoItems = toDoItems;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_to_do_list);

		EditText editText = (EditText) findViewById(R.id.new_todo);
		editText.setTextColor(getResources().getColor(
				android.R.color.holo_blue_dark));

		FragmentManager fm = getFragmentManager();

		toDoListFragment = (ToDoListFragment) fm
				.findFragmentById(R.id.toDo_list_container);
		if (toDoListFragment == null) {
			toDoListFragment = new ToDoListFragment();

			FragmentTransaction ft = fm.beginTransaction();
			ft.add(R.id.toDo_list_container, toDoListFragment);
			ft.commit();
		}

		toDoListArrayAdapter = new ToDoListArrayAdapter(this,
				R.layout.todo_list_item, toDoItems);
		toDoListArrayAdapter.setOnEditItemSelectListener(this);
		toDoListFragment.setListAdapter(toDoListArrayAdapter);
		ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setTitle("To Do List");
		actionBar.setIcon(R.drawable.ic_action_view_as_list);
		
	}

	@Override
	protected void onStop() {
		try {
			writeDataToFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		super.onStop();
		toDoItems.clear();
	}

	@Override
	protected void onStart() {
		toDoItems.clear();
		try {
			readDataFromFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		super.onStart();
	}

	public void writeDataToFile() throws IOException {
		String FILENAME = "toDo";
		FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
		JsonWriter jsonWriter = new JsonWriter(new OutputStreamWriter(fos,
				"UTF-8"));
		jsonWriter.beginArray();

		for (int i = 0; i < toDoItems.size(); i++) {
			jsonWriter.beginObject();
			jsonWriter.name("task").value(toDoItems.get(i).getTask());
			jsonWriter.name("checked").value(toDoItems.get(i).isChecked());
			jsonWriter.endObject();
		}

		jsonWriter.endArray();
		jsonWriter.close();
	}

	public void readDataFromFile() throws IOException {
		String FILENAME = "toDo";
		FileInputStream fis = openFileInput(FILENAME);
		if (fis != null) {
			JsonReader jsonReader = new JsonReader(new InputStreamReader(fis,
					"UTF-8"));
			jsonReader.beginArray();
			while (jsonReader.hasNext()) {
				toDoItems.add(readToDoItem(jsonReader));
			}
			jsonReader.endArray();
		}

	}

	public ToDoItem readToDoItem(JsonReader jsonReader) throws IOException {
		ToDoItem toDoItem = new ToDoItem();
		jsonReader.beginObject();
		while (jsonReader.hasNext()) {
			String name = jsonReader.nextName();
			if (name.equals("task")) {
				toDoItem.setTask(jsonReader.nextString());
			} else if (name.equals("checked")) {
				toDoItem.setChecked(jsonReader.nextBoolean());
			}
		}
		jsonReader.endObject();
		return toDoItem;

	}

	public void createItem() {
		EditText editText = (EditText) findViewById(R.id.new_todo);
		String task = editText.getText().toString();
		if (!task.isEmpty()) {
			ToDoItem toDoItem = new ToDoItem(task, false);

			toDoItems.add(toDoItem);
			toDoListArrayAdapter.notifyDataSetChanged();
			editText.setText("");

			InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			inputMethodManager.hideSoftInputFromWindow(
					editText.getApplicationWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.to_do_list, menu);
		this.menu = menu;
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.add_todo:
			createItem();
			return true;
		case R.id.delete_completedItems:
			for (Iterator<ToDoItem> iterator = toDoItems.iterator(); iterator
					.hasNext();) {
				if (iterator.next().isChecked()) {
					iterator.remove();
				}
			}
			toDoListArrayAdapter.notifyDataSetChanged();
			return true;
		case R.id.edit_todo:
			editItem();
			return true;
		case R.id.cancel_edit:
			cancelEditOperation();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}

	}
	
	public void cancelEditOperation(){
		EditText editText = (EditText) findViewById(R.id.new_todo);
		editText.setText("");
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(
				editText.getApplicationWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
		menu.findItem(R.id.edit_todo).setVisible(false);
		menu.findItem(R.id.add_todo).setVisible(true);
		menu.findItem(R.id.delete_completedItems).setVisible(true);
		menu.findItem(R.id.cancel_edit).setVisible(false);
	}

	public void editItem() {
		EditText editText = (EditText) findViewById(R.id.new_todo);
		int position = (Integer) editText.getTag(R.string.position);

		toDoItems.get(position).setTask(editText.getText().toString());
		editText.setText("");
		menu.findItem(R.id.edit_todo).setVisible(false);
		menu.findItem(R.id.add_todo).setVisible(true);
		menu.findItem(R.id.delete_completedItems).setVisible(true);
		menu.findItem(R.id.cancel_edit).setVisible(false);
		
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(
				editText.getApplicationWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
		
		toDoListArrayAdapter.notifyDataSetChanged();
	}

	public void deleteTodoItem(int position) {
		toDoItems.remove(position);
		toDoListArrayAdapter.notifyDataSetChanged();
	}

	@Override
	public void onEditItemSelected() {
		menu.findItem(R.id.edit_todo).setVisible(true);
		menu.findItem(R.id.add_todo).setVisible(false);
		menu.findItem(R.id.delete_completedItems).setVisible(false);
		menu.findItem(R.id.cancel_edit).setVisible(true);
		
	}

}
